<?php
class Sabai_Template_Default_Helper_XiggCategories extends Sabai_Template_Default_Helper
{
    function execute($prefix = ' - ', $script = SABAI_URL_SCRIPT)
    {
        $model =& $this->_locator->getService('Model');
        $category_r =& $model->getRepository('Category');
        $categories =& $category_r->fetchAll();
        $html = array();

        $entities = array();
        while ($category =& $categories->getNext()) {
            $parent_id = intval($category->getParentId());
            $entities[$parent_id]['children'][] =& $category;
            unset($category);
        }
        if (!empty($entities[0]['children'])) {
            foreach (array_keys($entities[0]['children']) as $i) {
                $this->_renderHTML($html, $entities, $entities[0]['children'][$i], $script, $prefix);
            }
        }
        return implode("<br />\n", $html);
    }

    function _renderHTML(&$html, $categories, &$category, $script, $prefixOrig, $prefix = '')
    {
        $id = $category->getId();
        array_push($html, sprintf('%s<a href="%s">%s</a>', $prefix, Sabai_URL::get('/', array('category_id' => $id), '', $script), h($category->getLabel())));
        if (!empty($categories[$id]['children'])) {
            foreach (array_keys($categories[$id]['children']) as $i) {
                $this->_renderHTML($html, $categories, $categories[$id]['children'][$i], $script, $prefixOrig, $prefix . $prefixOrig);
            }
        }
    }
}